<?php

namespace App\Repository;


use App\Models\Product;
use App\Repository\Enum\OrderStatusEnum;
use App\Repository\Wxpay\Database\WxPayNotify;

/**
 * 处理微信回调
 * Class WxNotifyRepository
 * @package App\Repository
 */
class WxNotifyRepository extends WxPayNotify
{
    /**
     * 处理微信回调，并返回处理结果
     * @param array $data
     * @param string $msg
     * @return bool
     */
    public function notifyProcess($data, &$msg)
    {
        if ($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];

            \DB::beginTransaction();
            try {
                $order = OrderRepository::getDataByOrderNo($orderNo);
                if ($order->status == 1){
                    $OrderRepository = new OrderRepository();
                    $stockStatus = $OrderRepository->checkOrderStock($order->id);
                    if ($stockStatus['pass']){
                        $this->updateOrderStatus($order->id, true);
                        $this->reduceStock($stockStatus);
                    }else{
                        //已支付但是库存不足
                        $this->updateOrderStatus($order->id, false);
                    }
                }
                \DB::commit();
                return true;
            }catch (\Exception $exception ){
                \DB::rollBack();
                \Log::info($exception);
                return false;
            }
        }else{
            return true; //通知微信停止回调
        }
    }

    /**
     * 更新订单状态
     * @param $id
     * @param $success
     */
    private function updateOrderStatus($id, $success)
    {
        $status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF ;
        OrderRepository::updateOrderStatusById($id, $status);
    }

    /**
     * 消减库存量
     */
    private function reduceStock($stockStatus)
    {
        foreach ($stockStatus['pStatusArray'] as $pStatusArray) {
            Product::where('id', $pStatusArray['id'])->decrement('stock', $stockStatus['count']);
        }
    }
}